/**   
 * @Title: LotteryAccountDetailListAct.java 
 * @Package: com.esun.rabbit2.viewer.mainact.mylotteryact.accountdetail 
 * @Description: TODO(购彩账户明细列表activity) 
 * @Author: Billy qigs@500wan.com   
 * @Date: 2011-7-27 下午04:46:42  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.accountdetail;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.AccountDetailListInfo;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.accountdetail.AccountDetailListCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.BeidanRecordDetailAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.LotteryRecordDetailAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.LotteryRecordDetailBasketballAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.LotteryRecordDetailFootballAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.ShengfurenjiuRecordDetailAct;
import com.esun.ui.R;
import com.esun.util.StringUtil;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: LotteryAccountDetailListAct
 * @Description: TODO(购彩账户明细列表activity)
 * @Author: Billy qigs@500wan.com
 * @Date: 2011-7-27 下午04:46:42
 */
public class LotteryListAct extends Activity implements OnItemClickListener, OnRefreshListener, OnScrollListener {

	private AccountDetailListCommunicater accountCommunicater;
	private PullToRefreshListView listViewAccountList;
	private ProgressDialog progressDialog;
	private LinearLayout linearFooter;
	private LinearLayout linearNoMore;
	private LinearLayout linearBottom;
	private ArrayList<Hashtable<String, String>> alItem;
	private AccountDetailListAdapter adapter;
	public static Handler accountDetailHandler;
	private LinearLayout linearNoRecord;

	private String serverMsg;
	private int pageno = 1;

	private boolean isRunning = false;
	private boolean isRefreshOrBottom = true;
	private boolean isNoMoreRecord = false;
	private boolean isShow = true;
	private boolean isScrollable = true;

	private static final int GET_ACCOUNT_DETAIL_SUCCEED = 1000001;
	private static final int GET_ACCOUNT_DETAIL_FAILED = 1000002;
	private static final String LOTTERY_ACCOUNT_LIST = "1";
	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final int FOOTER_VIEW_TAG3 = 30000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.accountdetaillist_act_lottery);

		initUI();
		initHandler();
	}

	public void initUI() {

		progressDialog = ViewerUtil.showProgressDialog(LotteryListAct.this, "加载中,请稍后...");
		progressDialog.show();
		linearNoRecord = (LinearLayout) findViewById(R.id.accountdetaillist_act_lottery_linear_noRecord);
		listViewAccountList = (PullToRefreshListView) findViewById(R.id.accountdetaillist_act_lottery_listview_total);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		linearNoMore.setTag(FOOTER_VIEW_TAG2);
		linearBottom.setTag(FOOTER_VIEW_TAG3);

		alItem = new ArrayList<Hashtable<String, String>>();
		adapter = new AccountDetailListAdapter(LotteryListAct.this, alItem);
		listViewAccountList.addFooterView(linearFooter);
		listViewAccountList.setAdapter(adapter);
		listViewAccountList.removeFooterView(linearFooter);
		listViewAccountList.setOnItemClickListener(this);
		listViewAccountList.setOnRefreshListener(this);
		listViewAccountList.setOnScrollListener(this);

		// listViewAccountList.onRefresh();
	}

	public void initHandler() {
		accountDetailHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				listViewAccountList.removeFooterView(linearBottom);
				switch (msg.what) {

				case GET_ACCOUNT_DETAIL_SUCCEED:

					pageno++;
					infoHandling(accountCommunicater.getAccountDetailList());
					EDebug.o(this, "通讯成功!" + pageno);
					if (accountCommunicater.getAccountDetailList().size() < 10) {
						isNoMoreRecord = false;
						listViewAccountList.addFooterView(linearNoMore);
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case GET_ACCOUNT_DETAIL_FAILED:

					lengthAutoAdapter();
					endProcess();
					EDebug.o(this, "通讯失败！");
					isScrollable = false;
					// 无更多记录
					if (accountCommunicater.getState() == 202 || accountCommunicater.getState() == 101) {
						isNoMoreRecord = false;
						if (pageno == 1) {
							// alItem.clear();
							linearNoRecord.setVisibility(View.VISIBLE);
						} else {
							listViewAccountList.addFooterView(linearNoMore);
						}
					} else {
						// 通讯失败
						if (isShow) {
							//ViewerUtil.showTipDialog(LotteryListAct.this, serverMsg, false);
							Toast.makeText(LotteryListAct.this, serverMsg, Toast.LENGTH_SHORT).show();
						}
					}

					break;

				case Config.CONNECTION_FAIL:

					EDebug.o(this, "连接失败！");
					isScrollable = false;
					showNoMoreRecordDialog(Language.STR_CONNECTIONFAIL);
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.DO_REFRESH:

					if (!isRunning) {
						listViewAccountList.prepareForRefresh();
						listViewAccountList.onRefresh();
						progressDialog.show();
					}
					AccountDetailListActGroup.isCanClick = true;
					break;

				default:

					break;
				}
			}
		};
	}

	private void endProcess() {
		if (isRefreshOrBottom) {
			listViewAccountList.onRefreshComplete();
		} else {
			listViewAccountList.removeFooterView(linearFooter);
		}
		if (progressDialog != null) {
			progressDialog.cancel();
		}
		isRunning = false;
	}

	public void getAccountDetailListThread() {
		new Thread() {

			@Override
			public void run() {

				super.run();
				accountCommunicater = new AccountDetailListCommunicater();
				Message msg = new Message();
				try {
					boolean isSucceed = accountCommunicater.isGetAccountDetailList(LOTTERY_ACCOUNT_LIST, String.valueOf(pageno));
					serverMsg = accountCommunicater.getErrorMSG();
					EDebug.o(this, accountCommunicater.getServerMsg());
					if (isSucceed) {
						msg = accountDetailHandler.obtainMessage(GET_ACCOUNT_DETAIL_SUCCEED, null);
						accountDetailHandler.sendMessage(msg);
					} else {
						msg = accountDetailHandler.obtainMessage(GET_ACCOUNT_DETAIL_FAILED, null);
						accountDetailHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					// TODO: handle exception
					msg = accountDetailHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					accountDetailHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

		if (firstVisibleItem + visibleItemCount == totalItemCount) {
			if (isNoMoreRecord) {
				if (!isRunning && alItem.size() != 0 && isScrollable) {
					EDebug.o(this, "到底加载...");
					isRunning = true;
					listViewAccountList.addFooterView(linearFooter);
					isRefreshOrBottom = false;
					getAccountDetailListThread();
				}
			}
		} else {
			isScrollable = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onRefresh() {

		if (!isRunning) {
			EDebug.o(this, "刷新...");
			pageno = 1;
			groupCount = 0;
			childCount = 0;
			isRunning = true;
			isNoMoreRecord = true;
			isRefreshOrBottom = true;
			if (listViewAccountList.getFooterViewsCount() != 0) {
				listViewAccountList.removeFooterView(linearNoMore);
			}
			linearNoRecord.setVisibility(View.GONE);
			getAccountDetailListThread();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		if (arg1.getTag() != null
				&& (Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG || Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG2 || Integer.parseInt(String.valueOf(arg1
						.getTag())) == FOOTER_VIEW_TAG3)) {
			return;
		} else {
			// 由于存储列表与现实list存在一位的偏移，故使用arg2-1
			Hashtable<String, String> temp_hashtable = new Hashtable<String, String>();
			temp_hashtable = alItem.get(arg2 - 1);
			// 操作种类
			String op_type = temp_hashtable.get(Key.KEY_TYPEID);
			// 彩种编号
			String temp_lotID = temp_hashtable.get(Key.KEY_LOTID);
			// 1-购彩、52-派奖、46-撤单可查看详情
			if (op_type.equals(Config.NUM1) || op_type.equals(Config.USERACTION_PAIJIANG) || op_type.equals(Config.USERACTION_CHEDAN)) {
				// 组织传入参数
				Bundle bundle = new Bundle();
				bundle.putString(Key.KEY_LOTID, temp_hashtable.get(Key.KEY_LOTID));
				bundle.putString(Key.KEY_ID, temp_hashtable.get(Key.KEY_PID));
				bundle.putString(Key.KEY_WINMONEY, temp_hashtable.get(Key.KEY_MONEY));

				// 分彩种进行操作
				if (temp_lotID.equals(Config.SHUANGSEQIU)) {
					// 双色球
					startActivity(new Intent(LotteryListAct.this, LotteryRecordDetailAct.class).putExtras(bundle));
				} else if (temp_lotID.equals(Config.DALETOU)) {
					// 大乐透
					startActivity(new Intent(LotteryListAct.this, LotteryRecordDetailAct.class).putExtras(bundle));
				} else if (temp_lotID.equals(Config.SHIYIXUANWU)) {
					// 11选5 判断是否为一周以内的记录，否则无法查看详情
					if (StringUtil.getDifferValue(temp_hashtable.get(Key.KEY_SERVERTIME), temp_hashtable.get(Key.KEY_DATE)) > Integer.valueOf(Config.NUM7)) {
						Toast.makeText(LotteryListAct.this, Language.MSG_RECORD_WUFACHAKAN, Toast.LENGTH_SHORT).show();
					} else {
						startActivity(new Intent(LotteryListAct.this, LotteryRecordDetailAct.class).putExtras(bundle));
					}
				} else if (temp_lotID.equals(Config.FUCAI3D)) {
					// 福彩3D
					startActivity(new Intent(LotteryListAct.this, LotteryRecordDetailAct.class).putExtras(bundle));
				} else if (temp_lotID.equals(Config.JINGCAIZUQIU)) {
					// 竞彩足球
					startActivity(new Intent(LotteryListAct.this, LotteryRecordDetailFootballAct.class).putExtras(bundle));
				} else if (temp_lotID.equals(Config.JINGCAILANQIU)) {
					// 竞彩篮球
					startActivity(new Intent(LotteryListAct.this, LotteryRecordDetailBasketballAct.class).putExtras(bundle));
					// Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.BEIJINGZUQIUDANCHANG)) {
					// 北京单场
					startActivity(new Intent(LotteryListAct.this, BeidanRecordDetailAct.class).putExtras(bundle));
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.SHENGFUCAI)) {
					// 足球胜负
					startActivity(new Intent(LotteryListAct.this, ShengfurenjiuRecordDetailAct.class).putExtras(bundle));
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.RENXUANJIU)) {
					// 任选九场
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.LIUCHANGBANQUAN)) {
					// 六场全半
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.SICHANGJINQIU)) {
					// 四场进球
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.ERSHIERXUANWU)) {
					// 22选5
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.PAILIESAN)) {
					// 排列三
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.PAILIEWU)) {
					// 排列五
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.QIXINGCAI)) {
					// 七星彩
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.QILECAI)) {
					// 七乐彩
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.KUAILESHIFEN)) {
					// 快乐十分
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else if (temp_lotID.equals(Config.SHISHICAI)) {
					// 时时彩
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				} else {
					// 其他情况
					Toast.makeText(LotteryListAct.this, "暂不支持此彩种", Toast.LENGTH_SHORT).show();
					EDebug.o(this, "lot id = " + alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				}

			}
		}
	}

	@Override
	protected void onPause() {

		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {

		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
		if (UserInfo.getUserInfo().isRebuy()) {
			getParent().finish();
		}
	}

	/* 显示提示框* */
	public void showNoMoreRecordDialog(String strMsg) {
		if (isShow) {
			ViewerUtil.showTipDialog(LotteryListAct.this, strMsg, false);
		}
	}

	public void infoHandling(ArrayList<AccountDetailListInfo> list) {
		ArrayList<Hashtable<String, String>> listTemp = new ArrayList<Hashtable<String, String>>();
		for (int i = 0; i < list.size(); i++) {
			Hashtable<String, String> map = new Hashtable<String, String>();

			String[] strDate = list.get(i).getOpTime().split(" ");

			map.put(Key.KEY_DATE, strDate[0]);
			map.put(Key.KEY_TIME, strDate[1]);
			map.put(Key.KEY_INOUT, list.get(i).getOpType());
			map.put(Key.KEY_MONEY, list.get(i).getMoney());
			map.put(Key.KEY_BALANCE, list.get(i).getBalance());
			map.put(Key.KEY_LOTID, list.get(i).getLotType());
			map.put(Key.KEY_NOTE, list.get(i).getNote());
			map.put(Key.KEY_TYPEID, list.get(i).getTypeID());
			map.put(Key.KEY_REMARK, list.get(i).getRemarks());
			map.put(Key.KEY_PID, list.get(i).getPid());
			EDebug.o(this, list.get(i).getPid());
			map.put(Key.KEY_SERVERTIME, list.get(i).getServerTime());

			listTemp.add(map);
		}

		if (isRefreshOrBottom) {
			alItem.clear();
			alItem.addAll(listTemp);
			adapter.notifyDataSetChanged();
		} else {
			alItem.addAll(listTemp);
			adapter.notifyDataSetChanged();
		}
	}

	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		adapter.countCalculate();
		groupCount = adapter.getGroupCount();
		childCount = adapter.getChildCount();

		int itemHeight = groupCount * (30 + 90) + childCount * 90;

		// 判断是否需要加入额外item
		if (itemHeight < listViewAccountList.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			linearChild.setBackgroundColor(Color.WHITE);
			if (listViewAccountList.getFooterViewsCount() > 0) {
				bheight = listViewAccountList.getHeight() - itemHeight - 30;
			} else {
				bheight = listViewAccountList.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			linearChild.setBackgroundColor(Color.WHITE);
			listViewAccountList.addFooterView(linearBottom);
		}
	}
}
